package com.ly.upload.web;

import com.ly.upload.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    @Value("${ly.upload.upload-dir}")
    private String uploadDir;
    @Value("${ly.upload.web-path}")
    private String webPath;

    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 随机生成文件名
        String filename = UUID.randomUUID().toString();
        filename = filename.replaceAll("-","");
        // 获取源文件名后缀
        final String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        // 拼接完整的文件名
        filename += suffix;
        // 本地路径
        String filepath = uploadDir + "/" + filename;
        // 保存到本地路径
        file.transferTo(new File(filepath));
        // 返回web路径
        return new Result(1,"文件上传成功!", webPath + "/" + filename);
    }

}
